<?php 
require_once 'common/common.inc.php';
require_once 'common/mail.inc.php';

$selected_date = isset($_REQUEST["date"]) ? $_REQUEST["date"] : "";
$selected_start_time = isset($_REQUEST["start_time"]) ? $_REQUEST["start_time"] : "";
$selected_minutes = isset($_REQUEST["minutes"]) ? $_REQUEST["minutes"] : "";
$location_name = isset($_REQUEST["location_name"]) ? $_REQUEST["location_name"] : "";;
$error = isset($_REQUEST["error"]) ? $_REQUEST["error"] : "";
$start_datetime = $selected_date.' '.$selected_start_time;

$start_date = new DateTimeDutch("@".strtotime($start_datetime), $timezone);
$start_date->setTimezone($timezone); 
$schedule_id = null;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

  conn();

  $result = mysql_query("SELECT NAME FROM LOCATIONS  WHERE CODE = '$location_code'");
  if (!$result) {die('Could not exec query: ' . mysql_error());}
  $row = mysql_fetch_array($result, MYSQL_ASSOC);
  $location_name = $row["NAME"];
  
  // check : schedule exists
  if (empty($error)) 
  {
    $sql = "";
    $sql .= "SELECT ID, NAME, START, END, DATE_FORMAT(START,'%Y-%m-%d') START_SHORT_ISO ";
    $sql .= "FROM SCHEDULES ";
    $sql .= "WHERE LOCATION_CODE = '$location_code' ";
    $sql .= "AND DATE_FORMAT(START,'%Y-%m-%d') <= '$selected_date' ";
    $sql .= "AND DATE_FORMAT(END,'%Y-%m-%d') >= '$selected_date' ";
    
    $result = mysql_query($sql);
    if (!$result) {die('Could not exec query: ' . mysql_error());}
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    
    if (!isset($row["ID"])) {
      $error = "Het bijbehorende schedule is niet gevonden.";
    } else {
      $schedule_id = $row["ID"];
    }
  }   

  // check : email has reservation already
  if (empty($error)) 
  {
    $sql = "";
    $sql .= "SELECT ID ";
    $sql .= "FROM RESERVATIONS ";
    $sql .= "WHERE SCHEDULE_ID = $schedule_id ";
    $sql .= "AND UPPER(SIGN_IN_EMAIL) = UPPER('".mysql_escape($email)."') ";

    $result = mysql_query($sql);
    if (!$result) {die('Could not exec query: ' . mysql_error());}
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    
    if (isset($row["ID"])) {
      $error = "Je hebt al een reservering op deze dag. Deze moet je eerst verwijderen.";
    }
  }

  // check : reservation already made
  if (empty($error)) 
  {
    $sql = "";
    $sql .= "SELECT ID ";
    $sql .= "FROM RESERVATIONS ";
    $sql .= "WHERE SCHEDULE_ID = $schedule_id ";
    $sql .= "AND START = '$start_datetime' ";

    $result = mysql_query($sql);
    if (!$result) {die('Could not exec query: ' . mysql_error());}
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
  
    if (isset($row["ID"])) {
      $error = "Deze datum is reeds gereserveerd. Kies een andere datum.";
    }
  }

  // check : is border reservation
  if (empty($error)) 
  {
    $sql = "";
    $sql .= "SELECT ID, START, END, CAST(CONFIRMED AS unsigned int) CONFIRMED ";
    $sql .= "FROM RESERVATIONS ";
    $sql .= "WHERE SCHEDULE_ID = $schedule_id ";
  
    $result = mysql_query($sql);
    if (!$result) {die('Could not exec query: ' . mysql_error());}
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
  
    $isFirst = false;
    if (!isset($row["ID"])) {
      $isFirst = true;
    } 

    if (!$isFirst) {
    
      // 2012-01-18 08:40:00 (TRY)
      // 2012-01-18 09:00:00 (EXISTS)
      // SELECT ADDTIME('2012-01-18 09:00:00', '00:20:00');
      // SELECT ADDTIME('2012-01-18 09:00:00', '-00:20:00');
      $sql = "";
      $sql .= "SELECT ID, START, END, CAST(CONFIRMED AS unsigned int) CONFIRMED ";
      $sql .= "FROM RESERVATIONS ";
      $sql .= "WHERE SCHEDULE_ID = $schedule_id ";
      $sql .= "AND ( START = ADDTIME('$start_datetime','00:$timePeriod:00') " ;
      $sql .= "   OR START = ADDTIME('$start_datetime','-00:$timePeriod:00') ) ";

      $result = mysql_query($sql);
      if (!$result) {die('Could not exec query: ' . mysql_error());}
      $row = mysql_fetch_array($result, MYSQL_ASSOC);
    
      if (!isset($row["ID"])) {
        $error = "Deze datum kan niet gereserveerd. Kies een andere datum.";
      } 
    }
  }
  
  // execute reservation
  if (empty($error)) 
  {
    $guid = uniqid("".$schedule_id."_", true);
    $sql = "INSERT INTO RESERVATIONS (START, END, SCHEDULE_ID, SIGN_IN_EMAIL, GUID, CREATE_DATE) ";
    $sql .= "VALUE ";
    $sql .= "('$start_datetime',ADDTIME('$start_datetime','00:$timePeriod:00'),$schedule_id,'".mysql_escape($email)."','$guid', NOW()) ";
    //echo $sql;
    $result = mysql_query($sql);
    if (!$result) {die('Could not exec query: ' . mysql_error());}
    $reservation_id = mysql_insert_id();
    
    if (!isset($reservation_id) || empty($reservation_id)) {
      $error = "De reservering kon niet gemaakt worden. Neem contact op met de beheerder of probeer het opnieuw.";
    } else {
      $tmp = preg_split("/-/",$selected_date);
      $selected_date_nl = $tmp['2']."-".$tmp['1']."-".$tmp['0'];
      $confirm_page = "05_confirm_reservation.php";
      $mail_template = "common/mail.message.confirm.knippen.html";
      sendAskConfirmationMail();
    }
  }

  close();
  
  // redirect to the same page without the POST data
  header("Location: ".$_SERVER['PHP_SELF']."?date=$selected_date&start_time=$selected_start_time&minutes=$selected_minutes&error=$error&location_name=$location_name");
  die;
}

?>

<?php 
include 'common/page.begin.inc.php';
?>

<body>

<div id="wrapper">

  <?php 
  $menuSelected = "diensten";
  $subMenuSelected = "knippen";
  include 'common/body.header.inc.php';
  ?>

  <div id="page" class="container">
  
    <div id="content">

      <?php
      $contentPath = "Knippen &gt;&gt; Afspraak Maken";
      include 'common/body.content.header.inc.php';
      ?>
      
      <div class="main-top">
        <div class="first knippen">
        </div>  
        <div class="second">
          <div class="content-blok">
      
            <?php 
            include 'common/body.error.inc.php';
            ?>
    
            <?php if (!empty($error)) { ?>
            
              <p>
                <a href="01_knippen.php">Klik hier om een nieuwe afspraak te maken.</a>
              </p>
              
            <?php } else { ?>
            
              <h2>Hartelijk dank voor je reservering via RedJeZaterdag.nl!</h2>
            
              <p>
                Je afspraak is vastgelegd op:<br />
                <?php echo $start_date->format('l d F Y \o\m H:i');?> (duur 20 min.)
              </p>
              <p>
                Op locatie:<br />
                <?php echo $location_name;?> 
              </p>

              <p>
                Om je reservering definitief te maken is er een e-mail naar je gestuurd. Klik op de link in deze e-mail om jouw reservering te bevestigen.
              </p>
              
              <p class="alert_text">
                LET OP: Om deze reservering definitief te maken moet je binnen <b>15</b> minuten op de link in deze e-mail klikken. 
                Deze werkwijze zorgt ervoor dat je <b>niet</b> met een password hoeft in te loggen en voorkomt misbruik.
              </p>
              
            <?php } ?>
            
          </div><!-- end content blok -->  
        </div><!-- end second -->  
      </div><!-- end home top -->

    </div><!-- end content -->

    <div style="clear: both;"></div>
	</div><!-- end page -->  
  
  <?php 
  include 'common/body.footer.inc.php';
  ?>
  
</div><!-- end wrapper -->

<?php 
include 'common/page.end.inc.php';
?>


